import 'package:flui/flui.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fzcgx_app/common/adapter_utils.dart';
import 'package:fzcgx_app/network/http.dart';
import 'package:fzcgx_app/ui/widget/my_underline_indicator.dart';

class SelectAddressWidget extends StatefulWidget {
  final Function valueCb;
  SelectAddressWidget({Key key, this.valueCb}) : super(key: key);
  @override
  _SelectAddressWidgetState createState() => _SelectAddressWidgetState();
}

class _SelectAddressWidgetState extends State<SelectAddressWidget>
    with SingleTickerProviderStateMixin {
  ///区域信息列表
  List localList;

  ///TabBarController
  TabController _tabController;

  ///选择的省市县的名字
  String selectProvinceStr = '省份';
  String selectCityStr = '城市';
  String selectDistrictStr = '区/县';

  ///选择的省市县Id
  String selectProvinceId = '';
  String selectCityId = '';
  String selectDistrictId = '';

  ///当前Tab位置
  int currentTabPos = 0;

  Map selectMap = new Map();

  ///Tab Text样式
  TextStyle tabTvStyle = new TextStyle(
      color: Colors.black, fontSize: 18.0, fontWeight: FontWeight.w300);
  @override
  void initState() {
    ///给区域Id Map一个初始值
    selectMap['selectProvinceId'] = -1;
    selectMap['selectCityId'] = -1;
    selectMap['selectDistrictId'] = -1;

    ///初始化控制器
    _tabController = new TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      ///获取tab当前点击位置
      currentTabPos = _tabController.index;

      ///切换Tab重新请求列表数据
      if (_checkTabCanSelect(currentTabPos)) {
        if (currentTabPos > 2) {
          return;
        }
        _requestApi(currentTabPos == 0
            ? ''
            : currentTabPos == 1 ? selectProvinceId : selectCityId);
      }

      print(currentTabPos);
    });
    _requestApi('');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        ///去掉左箭头
        automaticallyImplyLeading: false,
        title: new Text(
          '配送至',
          style: TextStyle(
              color: Color(0xff141F33),
              fontWeight: FontWeight.w600,
              fontSize: AdapterUtils.getSp(18)),
        ),
        centerTitle: true,
        elevation: 0.5,
        backgroundColor: Colors.white,
        actions: [
          new IconButton(
              icon: new Icon(
                Icons.close,
                color: const Color(0xff99A2AD),
              ),
              onPressed: () => Navigator.pop(context))
        ],
      ),
      body: _getBody(),
    );
  }

  ///构建底部视图
  Widget _getBody() {
    if (_showLoadingDialog()) {
      return Center(
      child: CupertinoActivityIndicator(
        animating: true,
        radius: 20,
      ),
    );
    } else {
      return _buildContent();
    }
  }

  ///根据数据是否有返回显示加载条或者列表
  bool _showLoadingDialog() {
    if (localList == null || localList.length == 0) {
      return true;
    } else {
      return false;
    }
  }

  ///有数据时构建tab和区域列表
  Widget _buildContent() {
    return new Container(
      child: new Column(
        children: [
          new Padding(padding: const EdgeInsets.only(top: 18.0)),
          new TabBar(
            // indicatorColor: Colors.black,
            controller: _tabController,
            isScrollable: false,
            indicatorColor: Color(0xff99A2AD),
            indicatorWeight: AdapterUtils.getHeight(4),
            indicatorSize: TabBarIndicatorSize.label,
            indicatorPadding:
                EdgeInsets.only(bottom: AdapterUtils.getHeight(5)),
            indicator: MyUnderlineTabIndicator(
                borderSide: BorderSide(
                  width: 4.0,
                  color: Color(0xff99A2AD),
                ),
                wantWidth: AdapterUtils.getWidth(12),bottom: 0.0),
            labelColor: Color(0xff3B4859),
            labelStyle: TextStyle(
              fontSize: AdapterUtils.getSp(16),
              fontWeight: FontWeight.bold,
            ),
            unselectedLabelColor: Color(0xff3B4859),
            unselectedLabelStyle: TextStyle(
              fontSize: AdapterUtils.getSp(16),
              fontWeight: FontWeight.bold,
            ),
            tabs: [
              new Text(
                '$selectProvinceStr',
                style: tabTvStyle,
                maxLines: 1,
              ),
              new Text(
                '$selectCityStr',
                style: tabTvStyle,
                maxLines: 1,
              ),
              new Text(
                '$selectDistrictStr',
                style: tabTvStyle,
                maxLines: 1,
              ),
            ],
          ),
          new Padding(padding: const EdgeInsets.only(top: 18.0)),
          _buildListView(),
        ],
      ),
      color: Colors.white,
    );
  }

  ///构建列表
  Widget _buildListView() {
    return new Expanded(
        child: new ListView.builder(
      shrinkWrap: true,
      itemCount: localList.length,
      itemBuilder: (BuildContext context, int position) {
        return _buildListRow(position);
      },
    ));
  }

  ///构建子项
  Widget _buildListRow(int position) {
    return new ListTile(
      title: new Text(
        '${localList[position]['name']}',
        style: TextStyle(
              color: Color(0xff99A2AD),
              fontWeight: FontWeight.w500,
              fontSize: AdapterUtils.getSp(16)),
      ),
      onTap: () => _onLocalSelect(position),
    );
  }

  ///区域位置选择
  _onLocalSelect(int position) {
    _setSelectData(position);
  }

  ///设置选择的数据
  ///根据当前选择的列表项的position 和 Tab的currentTabPos
  ///@params position 当前列表选择的省或市或县的position
  _setSelectData(position) {
    if (currentTabPos == 0) {
      selectProvinceId = localList[position]['id'];
      selectProvinceStr = localList[position]['name'];
      selectMap['provinceId'] = selectProvinceId;
      setState(() {
        selectCityStr = '城市';
        selectDistrictStr = '区/县';
      });
      selectCityId = '';
      selectDistrictId = '';
    }

    if (currentTabPos == 1) {
      selectCityId = localList[position]['id'];
      selectCityStr = localList[position]['name'];
      selectMap['selectCityId'] = selectCityId;
      setState(() {
        selectDistrictStr = '区/县';
      });
      selectDistrictId = '';
    }
    if (currentTabPos == 2) {
      selectDistrictId = localList[position]['id'];
      selectDistrictStr = localList[position]['name'];
      selectMap['selectDistrictId'] = selectDistrictId;

      ///拼接区域字符串 回调给上个页面 关闭弹窗
      String localStr =
          selectProvinceStr + ' ' + selectCityStr + ' ' + selectDistrictStr;
      widget.valueCb(selectMap, localStr);
      Navigator.pop(context);
      return;
    }
    currentTabPos++;

    _tabController.animateTo(currentTabPos);

    if (currentTabPos < 2) {
      _requestApi(localList[position]['id']);
    }
  }

  ///检查是否可以选择下级Tab
  // ignore: missing_return
  bool _checkTabCanSelect(int position) {
    if (position == 0) {
      return true;
    }
    if (position == 1) {
      if (selectProvinceId.isEmpty) {
        _tabController.animateTo(0);
        _showSnack();
        return false;
      }
      return true;
    }

    if (position == 2) {
      if (selectProvinceId.isEmpty && selectCityId.isEmpty) {
        _tabController.animateTo(0);
        _showSnack();
        return false;
      }
      if (selectProvinceId.isNotEmpty && selectCityId.isEmpty) {
        _tabController.animateTo(1);
        _showSnack();
        return false;
      }
      return true;
    }
  }

  ///显示错误信息
  _showSnack() {
    // Scaffold.of(context).showSnackBar(
    //     new SnackBar(content: new Text('请先选择上级地区')));
    FLToast.showText(text: '请先选择上级地区');
  }

  ///查询区域信息
  _requestApi(String parentId) {
    Http.instance.post('city/index', {'pid': parentId}, onSuccess: (data) {
      // if (currentTabPos == 2) {
      //   String localStr = selectProvinceStr + ' ' + selectCityStr;
      //   widget.valueCb(selectMap, localStr);
      //   Navigator.pop(context);
      // }
      if (mounted) {
        setState(() {
          localList = data;
        });
      }
    }, onError: (error) {}, onFail: (fail) {});
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}
